using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using EntLibEC.Cmn;
using EntLibEC.Biz.Report;
using EntLibEC.Biz;

namespace EntLibEC.View.Report
{
	/// <summary>
	/// Summary description for SaleAnalysis.
	/// </summary>
	public partial class SaleReportByProduct : PageBase
	{
		protected EntLibEC.View.Cmn.StockProduct ucProduct;
		protected EntLibEC.View.Cmn.Manufacturer ucManufacturer;
		protected EntLibEC.View.Cmn.YNStatus ucIsWholeSale;
		protected EntLibEC.View.Cmn.Category ucCategory;
		protected EntLibEC.View.Cmn.PM ucPPM;

		private int numberSum = 0;
		private decimal costSum = 0m;
		private decimal saleSum = 0m;
	
		protected void Page_Load(object sender, System.EventArgs e)
		{
			base.CheckAccess((int)AppEnum.Privilege.SaleReportSearch,true ,null);
			txtDateFrom.Attributes["onclick"]= "javascript:calendar()";
			txtDateTo.Attributes["onclick"]= "javascript:calendar()";

			if ( !Page.IsPostBack )
			{
				ucIsWholeSale.BindStatus(true);
				ucCategory.BindCategory();
				ucPPM.BindPM(true);
                ucProductType.BindProductType(true);
				txtDateFrom.Text = DateTime.Now.ToString(AppConst.DateFormat).Substring(0,7) + "-01";
				txtDateTo.Text = DateTime.Now.ToString(AppConst.DateFormat);

				btnExport.Enabled = false;
			}	
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.DataGrid1.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemDataBound);

		}
		#endregion

		private bool checkForm()
		{
			if ( !checkDate(txtDateFrom, "Date From") || !checkDate(txtDateTo, "Date To"))
				return false;

			return true;

		}
		private bool checkDate(TextBox txt, string txtName)
		{
			if ( txt.Text.Trim() == "")
			{
				Assert(lblMessage, txtName + " can't be empty", -1);
				return false;
			}
			else
			{
				try
				{
					Convert.ToDateTime(txt.Text.Trim());
				}
				catch
				{
					Assert(lblMessage, txtName + " format error", -1);
					return false;
				}
			}
			return true;

		}
		protected void btnSearch_Click(object sender, System.EventArgs e)
		{
			if ( !checkForm())
				return;

			Hashtable ht = new Hashtable(10);
			ht.Add("DateFrom", txtDateFrom.Text.Trim());
			ht.Add("DateTo", txtDateTo.Text.Trim());
			if ( ucIsWholeSale.YNSysNo != AppConst.IntNull )
				ht.Add("IsWholeSale", ucIsWholeSale.YNSysNo);

			if ( ucPPM.PMSysNo != AppConst.IntNull)
				ht.Add("PPMUserSysNo", ucPPM.PMSysNo);

			if ( ucProduct.ProductSysNo != AppConst.IntNull)
				ht.Add("ProductSysNo", ucProduct.ProductSysNo);

			if ( txtProductName.Text.Trim() != "")
				ht.Add("ProductName", txtProductName.Text.Trim());

			if ( ucManufacturer.ManuSysNo != AppConst.IntNull )
				ht.Add("ManufacturerSysNo", ucManufacturer.ManuSysNo);

			if ( ucCategory.C3SysNo != AppConst.IntNull )
				ht.Add("Category", " c3sysno= " + ucCategory.C3SysNo);
			else if ( ucCategory.C2SysNo != AppConst.IntNull )
				ht.Add("Category", " c2sysno= " + ucCategory.C2SysNo);
			else if ( ucCategory.C1SysNo != AppConst.IntNull )
				ht.Add("Category", " c1sysno= " + ucCategory.C1SysNo);

			if ( Convert.ToInt32( ddlTop.SelectedItem.Value ) != -999 )
				ht.Add("TOP", Convert.ToInt32(ddlTop.SelectedItem.Value));

            if (ucProductType.ProductTypeSysNo != AppConst.IntNull)
                ht.Add("ProductType", ucProductType.ProductTypeSysNo);

			ht.Add("OrderBy", ddlOrderBy.SelectedItem.Value);


			DataSet ds = ReportManager.GetInstance().GetSaleAnalysisDs(ht);

			DataGrid1.DataSource = ConvertDs(ds);
			DataGrid1.DataBind();

			int rows = 0;
			if ( Util.HasMoreRow(ds) )
			{
				rows = ds.Tables[0].Rows.Count;
				btnExport.Enabled = true;
			}
			Assert(lblMessage, rows.ToString() + " record(s)", 1);
		
		}

		private DataSet ConvertDs(DataSet ds)
		{
			if ( !Util.HasMoreRow(ds))
				return null;

			ds.Tables[0].Columns.Add("TotalAmt");
			ds.Tables[0].Columns.Add("ProfitCvt");
			ds.Tables[0].Columns.Add("ProfitRate");

			ds.Tables[0].Columns.Add("CurrentPriceCvt");
			ds.Tables[0].Columns.Add("UnitCostCvt");
			ds.Tables[0].Columns.Add("ProductCostSumCvt");
			ds.Tables[0].Columns.Add("TotalCostCvt");
			ds.Tables[0].Columns.Add("TotalSaleCvt");
			ds.Tables[0].Columns.Add("RateCvt");
			
			foreach( DataRow dr in ds.Tables[0].Rows )
			{
				decimal currentPrice = Util.TrimDecimalNull(dr["CurrentPrice"]);
				dr["CurrentPriceCvt"] = currentPrice.ToString(AppConst.DecimalFormatWithGroup);

				decimal unitCost = Util.TrimDecimalNull(dr["UnitCost"]);
				dr["UnitCostCvt"] = unitCost.ToString(AppConst.DecimalFormatWithGroup);

				decimal productcostsum = Util.TrimDecimalNull(dr["productcostsum"]);
				dr["ProductCostSumCvt"] = (productcostsum/1.17m).ToString(AppConst.DecimalFormatWithGroup);

				decimal totalCost = Util.TrimDecimalNull(dr["totalCost"]);
				dr["TotalCostCvt"] = (totalCost/1.17m).ToString(AppConst.DecimalFormatWithGroup);

				decimal totalSale = Util.TrimDecimalNull(dr["totalSale"]);
				dr["TotalSaleCvt"] = (totalSale/1.17m).ToString(AppConst.DecimalFormatWithGroup);

				dr["ProfitCvt"] = (Util.TrimDecimalNull(dr["Profit"]) /1.17m).ToString(AppConst.DecimalFormatWithGroup);

				decimal rate = Util.TrimDecimalNull(dr["rate"]);
				if ( rate == -1.0m)
					dr["RateCvt"] = "N/A";
				else
					dr["RateCvt"] = (rate * 100).ToString(AppConst.DecimalFormat) + "%";

				numberSum += Util.TrimIntNull(dr["TotalNumber"]);
				costSum += totalCost;
				saleSum += totalSale;

			}
			return ds;
		}

		private string ToFooterString(int x)
		{
			if ( x == 0)
				return "";
			return x.ToString(AppConst.IntFormatWithGroup);
		}
		private string ToFooterString(decimal x)
		{
			if ( x == 0)
				return "";
			return x.ToString(AppConst.DecimalFormatWithGroup);
		}

		private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
		{
			if(e.Item.ItemType == ListItemType.Footer)
			{
				e.Item.Cells[2].Text = ToFooterString(numberSum);
				e.Item.Cells[8].Text = ToFooterString(costSum/1.17m);
				e.Item.Cells[9].Text = ToFooterString(saleSum/1.17m);
				e.Item.Cells[10].Text = ToFooterString((saleSum -costSum)/1.17m);

				if ( saleSum != 0)
					e.Item.Cells[11].Text = ( ((saleSum-costSum) / saleSum) * 100).ToString(AppConst.DecimalFormat) + "%";
				else
					e.Item.Cells[11].Text = "N/A";
			}
		}

		protected void btnExport_Click(object sender, System.EventArgs e)
		{
			Util.ToExcel(DataGrid1, "Sale Report by product", "");
		}
	}
}
